package com.dean.ui.panel.impl;

import com.dean.action.DataFileImpExpAction;
import com.dean.entity.DataFileImpExpEntity;
import com.dean.entity.DataQueryEntity;
import com.dean.entity.DeanResponse;
import com.dean.service.DbConnService;
import com.dean.ui.constant.ConponentType;
import com.dean.ui.panel.DeanPanel;
import com.dean.ui.utils.UiUtils;
import com.dean.utils.DeanJdbcUtils;
import com.dean.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.UUID;

/**
 * @ClassName 数据文件导入导出
 * @Description csv 导入面板
 * @Author dean
 * @Date 2021/10/3 10:03
 */
public class DataFileImpExpPanel extends BasePanel implements DeanPanel {

    private static final Logger logger = LoggerFactory.getLogger(DataFileImpExpPanel.class);

    /**
     * 配置文件名称
     */
//    private final String INIT_PATH_NAME = DeanUiConstants.INIT_PATH + "datafile.properties";
    private JFrame frame;
    private JDialog dialog;
    private JPanel connNamePanel;
    private JLabel connNameLable;
    private JComboBox<String> connName;

    private JPanel optTypePanel;
    private JLabel optTypeLable;
    private JComboBox<String> optType;

    private JPanel fileTypePanel;
    private JLabel fileTypeLable;
    private JComboBox<String> fileType;

    private JPanel filePathPanel;
    private JLabel filePathLable;
    private JTextField filePath;


    private JPanel tableNamePanel;
    private JLabel tableNameLable;
    private JTextField tableName;

    private JPanel delimiterPanel;
    private JLabel delimiterLable;
    private JTextField delimiter;

    private JPanel commitNumPanel;
    private JLabel commitNumLable;
    private JTextField commitNum;

    private JPanel exeCfgPanel;
    private JLabel exeCfgLable;
    private JTextArea exeCfg;
    private JScrollPane exeCfgScollPane;

    private JPanel dataIdPanel;
    private JLabel dataIdLable;
    private JTextField dataId;

    private JPanel btnPanel;
    private JButton queryBtn;
    private JButton addBtn;
    private JButton editBtn;
    private JButton delBtn;
    private JButton exeBtn;
    private JButton subBtn;
    private JButton cancleBtn;


    private JTable table;
    private JScrollPane tablelPane;

    private String operation;
    private JLabel queryConditionLable;
    private JTextField queryCondition;


    @Override
    public void mainUi() {
        int startRow = 1;
        queryConditionLable = new JLabel("查询条件sql方式");
        UiUtils.setBounds(queryConditionLable,startRow,1,1,2, ConponentType.LABLE);
        panel.add(queryConditionLable);
        queryCondition = new JTextField();
        UiUtils.setBounds(queryCondition,startRow,1,1,2, ConponentType.INPUT);
        panel.add(queryCondition);
        startRow++;

        // 查询
        queryBtn = new JButton("查询");
        UiUtils.setLeftButtonBounds(queryBtn,startRow,1);
        panel.add(queryBtn);

        addBtn = new JButton("添加");
        UiUtils.setLeftButtonBounds(addBtn,startRow,2);
        panel.add(addBtn);

        editBtn = new JButton("修改");
        UiUtils.setLeftButtonBounds(editBtn,startRow,3);
        panel.add(editBtn);

        // 执行按钮
        delBtn = new JButton("删除");
        UiUtils.setLeftButtonBounds(delBtn,startRow,4);
        panel.add(delBtn);

        // 执行按钮
        exeBtn = new JButton("执行任务");
        UiUtils.setLeftButtonBounds(exeBtn,startRow,5);
        panel.add(exeBtn);

        startRow++;

        // 查询列表窗口
        table = new JTable();
        tablelPane = new JScrollPane(table);
        table.setShowGrid(true);
        UiUtils.setTableBounds(tablelPane,startRow);
        panel.add(tablelPane);
        setDialog();
    }

    private void setDialog(){
        frame = new JFrame("添加导入或者导出配置");
        frame.setPreferredSize(new Dimension(UiUtils.screenWidth/2,UiUtils.screenHeight/5*3));
        dialog = new JDialog(frame,"添加导入或者导出配置");
        dialog.setSize(UiUtils.screenWidth/2,UiUtils.screenHeight/5*3);
        dialog.setLocation(UiUtils.screenWidth/4,UiUtils.screenHeight/5);
        dialog.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));

        connNamePanel = new JPanel();
        connNamePanel.setPreferredSize(new Dimension(UiUtils.colLen,UiUtils.eleHeight+UiUtils.elePadding));
        connNameLable = new JLabel("数据库连接名称:");
        connNameLable.setPreferredSize(new Dimension(UiUtils.labelWidth,UiUtils.eleHeight));
        connNamePanel.add(connNameLable);
        connName = new JComboBox<String>();
        connName.setPreferredSize(new Dimension(UiUtils.inputWidth,UiUtils.eleHeight));
        connNamePanel.add(connName);
        dialog.add(connNamePanel);

        optTypePanel = new JPanel();
        optTypePanel.setPreferredSize(new Dimension(UiUtils.colLen,UiUtils.eleHeight+UiUtils.elePadding));
        optTypeLable = new JLabel("操作类型:");
        optTypeLable.setPreferredSize(new Dimension(UiUtils.labelWidth,UiUtils.eleHeight));
        optTypePanel.add(optTypeLable);
        optType = new JComboBox<String>();
        optType.setPreferredSize(new Dimension(UiUtils.inputWidth,UiUtils.eleHeight));
        optTypePanel.add(optType);
        dialog.add(optTypePanel);

        fileTypePanel = new JPanel();
        fileTypePanel.setPreferredSize(new Dimension(UiUtils.colLen,UiUtils.eleHeight+UiUtils.elePadding));
        fileTypeLable = new JLabel("文件类型:");
        fileTypeLable.setPreferredSize(new Dimension(UiUtils.labelWidth,UiUtils.eleHeight));
        fileTypePanel.add(fileTypeLable);
        fileType = new JComboBox<String>();
        fileType.setPreferredSize(new Dimension(UiUtils.inputWidth,UiUtils.eleHeight));
        fileTypePanel.add(fileType);
        dialog.add(fileTypePanel);


        filePathPanel = new JPanel();
        filePathPanel.setPreferredSize(new Dimension(UiUtils.colLen,UiUtils.eleHeight+UiUtils.elePadding));
        filePathLable = new JLabel("文件路径:");
        filePathLable.setPreferredSize(new Dimension(UiUtils.labelWidth,UiUtils.eleHeight));
        filePathPanel.add(filePathLable);
        filePath = new JTextField("/dean/dean_tool_cfg/test/imp/test.txt");
        filePath.setPreferredSize(new Dimension(UiUtils.inputWidth,UiUtils.eleHeight));
        filePathPanel.add(filePath);
        dialog.add(filePathPanel);

        tableNamePanel = new JPanel();
        tableNamePanel.setPreferredSize(new Dimension(UiUtils.colLen,UiUtils.eleHeight+UiUtils.elePadding));
        tableNameLable = new JLabel("文件导入表名:");
        tableNameLable.setPreferredSize(new Dimension(UiUtils.labelWidth,UiUtils.eleHeight));
        tableNamePanel.add(tableNameLable);
        tableName = new JTextField();
        tableName.setPreferredSize(new Dimension(UiUtils.inputWidth,UiUtils.eleHeight));
        tableNamePanel.add(tableName);
        dialog.add(tableNamePanel);


        delimiterPanel = new JPanel();
        delimiterPanel.setPreferredSize(new Dimension(UiUtils.colLen,UiUtils.eleHeight+UiUtils.elePadding));
        delimiterLable = new JLabel("TXT文件分割符:");
        delimiterLable.setPreferredSize(new Dimension(UiUtils.labelWidth,UiUtils.eleHeight));
        delimiterPanel.add(delimiterLable);
        delimiter = new JTextField();
        delimiter.setPreferredSize(new Dimension(UiUtils.inputWidth,UiUtils.eleHeight));
        delimiterPanel.add(delimiter);
        dialog.add(delimiterPanel);

        commitNumPanel = new JPanel();
        commitNumPanel.setPreferredSize(new Dimension(UiUtils.colLen,UiUtils.eleHeight+UiUtils.elePadding));
        commitNumLable = new JLabel("每批提交记录数:");
        commitNumLable.setPreferredSize(new Dimension(UiUtils.labelWidth,UiUtils.eleHeight));
        commitNumPanel.add(commitNumLable);
        commitNum = new JTextField();
        commitNum.setPreferredSize(new Dimension(UiUtils.inputWidth,UiUtils.eleHeight));
        commitNumPanel.add(commitNum);
        dialog.add(commitNumPanel);


        exeCfgPanel = new JPanel();
        exeCfgPanel.setPreferredSize(new Dimension(UiUtils.colLen,UiUtils.labelWidth+UiUtils.elePadding));
        exeCfgLable = new JLabel("导入字段配置");
        exeCfgLable.setPreferredSize(new Dimension(UiUtils.labelWidth,UiUtils.labelWidth));
        exeCfgPanel.add(exeCfgLable);
        exeCfg = new JTextArea();
        // exeCfg.setPreferredSize(new Dimension(UiUtils.inputWidth-UiUtils.elePadding*2,UiUtils.labelWidth));
        exeCfgScollPane = new JScrollPane(exeCfg);
        exeCfgScollPane.setPreferredSize(new Dimension(UiUtils.inputWidth,UiUtils.labelWidth+UiUtils.elePadding));
        exeCfgScollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        exeCfgScollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        exeCfgPanel.add(exeCfgScollPane);
        dialog.add(exeCfgPanel);

        dataIdPanel = new JPanel();
        dataIdPanel.setVisible(false);
        dataIdPanel.setPreferredSize(new Dimension(UiUtils.colLen,UiUtils.eleHeight+UiUtils.elePadding));
        dataIdLable = new JLabel("数据ID:");
        dataIdLable.setPreferredSize(new Dimension(UiUtils.labelWidth,UiUtils.eleHeight));
        dataIdPanel.add(dataIdLable);
        dataId = new JTextField();
        dataId.setPreferredSize(new Dimension(UiUtils.inputWidth,UiUtils.eleHeight));
        commitNumPanel.add(dataId);
        dialog.add(dataIdPanel);


        btnPanel = new JPanel();
        btnPanel.setPreferredSize(new Dimension(UiUtils.colLen,UiUtils.eleHeight+UiUtils.elePadding));
        subBtn=new JButton("提交");
        cancleBtn = new JButton("取消");
        btnPanel.add(subBtn);
        btnPanel.add(cancleBtn);
        dialog.add(btnPanel);
    }

    @Override
    public void mainScript() {
        // 下拉框处理
        DbConnService.getInstance().getConnInfos().forEach(connInfo -> {
            connName.addItem(connInfo.getConnName());
        });
        connName.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    String connNameSelected = e.getItem().toString();
                    logger.debug("当前选中了{}", connNameSelected);
                }
            }
        });
        // 下拉框添加枚举值
        optType.addItem("文件导入");
        optType.addItem("文件导出");
        optType.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    String optTypeSelected = e.getItem().toString();
                    logger.debug("当前选中了{}", optTypeSelected);
                    if("文件导出".equals(optTypeSelected)){
                        exeCfgLable.setText("导出查询sql语句");
                        tableNamePanel.setVisible(false);
                    }else{
                        exeCfgLable.setText("导入字段配置");
                        tableNamePanel.setVisible(true);
                    }
                }
            }
        });

        fileType.addItem("TXT");
        fileType.addItem("EXCEL");

        exeBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int rownum = table.getSelectedRow();
                // 检验数据
                if(rownum == -1){
                    JOptionPane.showMessageDialog(panel, "请选择一条记录执行", "ERROR", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                DataFileImpExpEntity entity = new DataFileImpExpEntity();
                String connNameF = table.getValueAt(rownum,0).toString();
                String optTypeF = table.getValueAt(rownum,1).toString();
                String fileTypeF = table.getValueAt(rownum,2).toString();
                String filePathF = table.getValueAt(rownum,3).toString();
                String commitNumF = table.getValueAt(rownum,4).toString();
                String tableNameF = table.getValueAt(rownum,5).toString();
                String delimiterF = table.getValueAt(rownum,6).toString();
                String exeCfgF = table.getValueAt(rownum,7).toString();
                String dataIdF = table.getValueAt(rownum,8).toString();
                entity.setDataId(dataIdF);
                entity.setDelimiter(delimiterF);
                entity.setFilePath(filePathF);
                entity.setFileType(fileTypeF);
                entity.setConnName(connNameF);
                entity.setExeCfg(exeCfgF);
                entity.setCommitNum(commitNumF);
                entity.setOptType(optTypeF);
                entity.setTableName(tableNameF);
                DeanResponse deanResponse = DataFileImpExpAction.getInstance().execute(entity);
                if(deanResponse.getCode() == 0){
                    JOptionPane.showMessageDialog(panel, deanResponse.getMsg(), "SUCCESS", JOptionPane.INFORMATION_MESSAGE);
                }else{
                    JOptionPane.showMessageDialog(panel, deanResponse.getMsg(), "ERROR", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        queryBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String queryCon = queryCondition.getText();
                if(StringUtils.isBlank(queryCon)){
                    queryCon = "1=1";
                }
                String querySql = String.format("select * from sys_data_file_imp_exp where 1=1 and %s", queryCon);
                DataQueryEntity dataQueryEntity = DeanJdbcUtils.queryDataAndHead(querySql);
                if(dataQueryEntity.getCode() == 0){
                    DefaultTableModel tableModel = new DefaultTableModel(dataQueryEntity.getDatas(),dataQueryEntity.getHeader());
                    table.setModel(tableModel);
                }else{
                    JOptionPane.showMessageDialog(panel, dataQueryEntity.getMsg(), "ERROR", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                table.setVisible(true);
            }
        });

        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                operation="add";
                dialog.repaint();
                dialog.setModal(true);//设置对话框为模态
                dialog.setVisible(true);
            }
        });

        editBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                operation="edit";
                // 这里需要初始化值
                showDetail();
            }
        });

        delBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                operation="del";
                // 这里页面设置不可编辑
                // 打开有内容
                showDetail();
            }
        });

        subBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 组装数据
                DataFileImpExpEntity dataFileImpExp = genCfg();
                // 保存数据
                DataFileImpExpAction action = DataFileImpExpAction.getInstance();
                DeanResponse deanResponse = null;
                if("add".equals(operation)){
                    deanResponse = action.saveCfg(dataFileImpExp);
                }else if("edit".equals(operation)){
                    deanResponse = action.updateCfg(dataFileImpExp);
                }else if("del".equals(operation)){
                    deanResponse = action.delCfg(dataFileImpExp);
                }else{
                    JOptionPane.showMessageDialog(panel, "非法操作:"+operation, "ERROR", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if(deanResponse.getCode() == 0){
                    JOptionPane.showMessageDialog(panel, deanResponse.getMsg(), "SUCCESS", JOptionPane.INFORMATION_MESSAGE);
                    // 关闭弹窗
                    cancleBtn.doClick();
                    queryBtn.doClick();
                }else{
                    JOptionPane.showMessageDialog(panel, deanResponse.getMsg(), "ERROR", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        cancleBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
                //设置对话框为模态
                dialog.setModal(false);

            }
        });
    }

    private void showDetail(){

        int rownum = table.getSelectedRow();
        if(rownum == -1){
            JOptionPane.showMessageDialog(panel, "请选择一条记录", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(!"add".equals(operation)){
            String connNameF = table.getValueAt(rownum,0).toString();
            String optTypeF = table.getValueAt(rownum,1).toString();
            String fileTypeF = table.getValueAt(rownum,2).toString();
            String filePathF = table.getValueAt(rownum,3).toString();
            String commitNumF = table.getValueAt(rownum,4).toString();
            String tableNameF = table.getValueAt(rownum,5).toString();
            String delimiterF = table.getValueAt(rownum,6).toString();
            String exeCfgF = table.getValueAt(rownum,7).toString();
            String dataIdF = table.getValueAt(rownum,8).toString();
            connName.setSelectedItem(connNameF);
            optType.setSelectedItem(optTypeF);
            fileType.setSelectedItem(fileTypeF);
            filePath.setText(filePathF);
            commitNum.setText(commitNumF);
            tableName.setText(tableNameF);
            delimiter.setText(delimiterF);
            exeCfg.setText(exeCfgF);
            dataId.setText(dataIdF);
        }
        if("del".equals(operation)){
            connName.setEditable(false);
            optType.setEditable(false);
            fileType.setEditable(false);
            filePath.setEditable(false);
            commitNum.setEditable(false);
            tableName.setEditable(false);
            delimiter.setEditable(false);
            exeCfg.setEditable(false);
        }else{
            connName.setEditable(true);
            optType.setEditable(true);
            fileType.setEditable(true);
            filePath.setEditable(true);
            commitNum.setEditable(true);
            tableName.setEditable(true);
            delimiter.setEditable(true);
            exeCfg.setEditable(true);
        }
        dialog.setModal(true);//设置对话框为模态
        dialog.setVisible(true);
    }

    private DataFileImpExpEntity genCfg(){
        DataFileImpExpEntity dataFileImpExp = new DataFileImpExpEntity();
        if("add".equals(operation)){
            dataFileImpExp.setDataId(UUID.randomUUID().toString());
        }else{
            dataFileImpExp.setDataId(dataId.getText());
        }
        dataFileImpExp.setConnName(connName.getSelectedItem().toString());
        dataFileImpExp.setOptType(optType.getSelectedItem().toString());
        dataFileImpExp.setFileType(fileType.getSelectedItem().toString());
        dataFileImpExp.setFilePath(filePath.getText());
        dataFileImpExp.setTableName(tableName.getText());
        dataFileImpExp.setDelimiter(delimiter.getText());
        dataFileImpExp.setCommitNum(commitNum.getText());
        dataFileImpExp.setExeCfg(exeCfg.getText());
        return dataFileImpExp;
    }


    @Override
    public void initProperties() {
    }
}
